
import { Empty,Popconfirm, Tooltip } from 'antd';
import { scaleLinear } from 'd3-scale';
import moment from 'moment';
import React, { useContext } from 'react';
import { UserContext } from '@/layouts/UserProvider';
import { ScheduleContext } from '../SchContext';

const SHORT_TIME_FORMAT = 'HH:mm';

const EventItem = ({ data, left, top, width, onEventClick, onCheck }) => {
  const content = `${moment(data.start_time).format(SHORT_TIME_FORMAT)}-${moment(
    data.end_time,
  ).format(SHORT_TIME_FORMAT)}  ${data.taskTagName?data.taskTagName:''}（${data.content}）`;
  const userCtx = useContext(UserContext);
  if (data.status == 3) {
    return(<></>);
  }
  if (data.status == 1) {
    return (<>
      <div
      title={content}
      onClick={() =>  onEventClick && onEventClick(data)}
      className="event-entry"
      style={{
        left,
        top,
        width,
        backgroundColor: data.bgColor || 'rgba(204, 204, 204, 0.6)',
      }}
    >
      <div className="event-entry-inner">{content}</div>
      </div>
    </>);
  }
  //气泡弹窗
  return (
    <Popconfirm
      disabled={!(+data.status === 1 && ['1', '4'].includes(String(userCtx.userInfo?.type)) && userCtx.userPermits.includes('updateTask'))}
      icon={null}
      title={''}
      onCancel={() => onCheck({ record: data, id: data.car_appointment_id, status: 3 })}
      onConfirm={() => onCheck({ record: data, id: data.car_appointment_id, status: 2 })}
      >
      <div
        title={content}
        
        onClick={() => +data.status === 2 && onEventClick && onEventClick(data)}
        className="event-entry"
        style={{
          left,
          top,
          width,
          backgroundColor: data.bgColor || 'rgba(204, 204, 204, 0.6)',
        }}
      >
        <div className="event-entry-inner">{content}</div>
      </div>
    </Popconfirm>
  );
};

const EventItemList = ({ events, onEventClick, onSelect, resourceInfo, onCheck }) => {
  const ctx = useContext(ScheduleContext);
  const userCtx = useContext(UserContext)
  const scale = scaleLinear(
    [+moment(ctx.timeRange[0]), +moment(ctx.timeRange[ctx.timeRange.length - 1])],
    [0, ctx.timeRange.length - 1],
  ).clamp(true);
  const updateSelectedData = ({ time }) => {
    const timeA = +moment(ctx.selectItems?.from);
    const timeB = +moment(time);
    const timeC = +moment(ctx.selectItems?.to);
    ctx.setSelectItems({
      ...ctx.selectItems,
      ...(timeB < timeA && {
        from: timeB,
        to: timeC,
      }),
      ...(timeB > timeC && {
        from: timeA,
        to: timeB,
      }),
    });
  };
  const handleMouseEnter = ({ time }) => {
    if (ctx.selectEnabled) {
      // if (ctx.dateUnit === 'DAY' && (time< moment(time).hours(10).minutes(0) || time > moment(time).hours(15).minutes(0))) {
      //   message.info('仅支持10:00-15:00时间段内的预约！');
      //   updateSelectedData({ time: moment(time).hours(15).minutes(0).toDate() });
      // }else{
      // }
      updateSelectedData({ time });
    }
  };
  const handleMouseDown = ({ time, resource }) => {
    if (!userCtx.userPermits.includes('addTask')) {
      return
    }
    // if (ctx.dateUnit === 'DAY' && (time< moment(time).hours(10).minutes(0) || time > moment(time).hours(15).minutes(0))) {
    //   message.info('仅支持10:00-15:00时间段内的预约！')
    // } else {
    // }
    ctx.setSelectItems({
      resource,
      from: time,
      to: time,
    });
    ctx.setSelectEnabled(true);
  };
  const handleMouseUp = ({ time }) => {
    // if (ctx.dateUnit === 'DAY' && (time< moment(time).hours(10).minutes(0) || time > moment(time).hours(15).minutes(0))) {
    //   updateSelectedData({ time: moment(time).hours(15).minutes(0).toDate() });
    // }else{
    // }
    updateSelectedData({ time });
    ctx.setSelectEnabled(false);
    if (ctx.selectItems) {
      onSelect({...ctx.selectItems}, ctx.dateUnit);
    }
    ctx.setSelectItems(null);
  };
  const cells = ({ events = [], resource }) =>
    ctx.timeRange.map((time, tindex, list) => (
      <td
        onMouseEnter={() => handleMouseEnter({ time, resource })}
        onMouseDown={() => handleMouseDown({ time, resource })}
        onMouseUp={() => handleMouseUp({ time })}
        key={time}
        className={`cell table-cell ${
          String(ctx.selectItems?.resource?.card) === String(resource.card) &&
          +moment(time) >= +moment(ctx.selectItems?.from) &&
          +moment(time) <= +moment(ctx.selectItems?.to)
            ? 'selected'
            : ''
        }`}
      >
        <div className="table-cell-inner" style={{ height: events.length * 28 + 20 }} />
      </td>
    ));
  return (
    <tr>
      <td className="cell" style={{ height: 20, width: 150 }}>
        {events.map((event, index) => {
          const beginAnchor = scale(+moment(event.start_time));
          const endAnchor = scale(+moment(event.end_time));
          let offset = 0;
          let divHeight = document.getElementById('sch-table-box').offsetHeight;
          switch (ctx.dateUnit) {
            case 'DAY':
            case 'WEEK':
              if ((events.length * 28 + 20) + divHeight > 390) {
                offset = 152;
              } else {
                offset = 163;
              }
              break;
            default:
              offset = 152;
              break;
          }
          let left =  Math.floor(beginAnchor) * ctx.cellWidth + offset;
          let width =
            +moment(event.end_time) < +moment(ctx.timeRange[0]) ||
            +moment(event.start_time) > +moment(ctx.timeRange[ctx.timeRange.length - 1])
              ? 0
              : endAnchor === ctx.timeRange.length - 1
              ? (endAnchor - beginAnchor + 1) * ctx.cellWidth
              : (endAnchor - beginAnchor) * ctx.cellWidth;
          if (width < ctx.cellWidth && width > 0) {
            width = ctx.cellWidth;
            left = Math.floor(beginAnchor) * ctx.cellWidth + offset;
          }
          if (ctx.dateUnit !== 'DAY') {
            width = parseFloat(ctx.cellWidth);
          }
          return (
            <EventItem
              data={event}
              key={event.car_appointment_id}
              left={left}
              width={width}
              top={index * 28 + 10}
              onEventClick={onEventClick}
              onCheck={onCheck}
            />
          );
        })}
        <Tooltip title={resourceInfo.card}>
          <div
            className="table-cell-inner"
            style={{
              width: 150,
              overflow: 'hidden',
              textOverflow: 'ellipsis',
            }}
          >
            {resourceInfo.card}
          </div>
        </Tooltip>
      </td>
      {cells({ events, resource: resourceInfo })}
    </tr>
  );
};

const BobyEntity = ({ data, onEventClick, onSelect, onCheck }) => {
  const ctx = useContext(ScheduleContext);
  if (data.length === 0) {
    return (
      <tr>
        <td colSpan={ctx.timeRange.length + 1} rowSpan={2}>
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
        </td>
      </tr>
    );
  }
  return data.map(({ events = [], ...restInfo }, index) => (
    <EventItemList
      key={restInfo.card}
      events={events}
      resourceInfo={restInfo}
      onEventClick={onEventClick}
      onSelect={onSelect}
      onCheck={onCheck}
    />
  ));
};
const SchTBody = ({ onSelect, onEventClick, onCheck }) => {
  const ctx = useContext(ScheduleContext);
  if (ctx.timeRange.length === 0) return null;
  let data = [];
  let count = 0;
  for (let j = 0; j < ctx.normalResources.length; j++) {
    const element = ctx.normalResources[j].events;
    data[j] = ctx.normalResources[j];
    let events = [];
    let i = 0;
    for (let k = 0; k < element.length; k++) {
      if (element[k].status != 3) {
        events[i] = element[k];
        i++;
      }
    }
    count = count + i;
    data[j].events = events;
  }
  return (
    <tbody>
      <BobyEntity
        data={data}
        onEventClick={onEventClick}
        onSelect={onSelect}
        onCheck={onCheck}
      />
    </tbody>
  );
};

export default SchTBody;
